/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package korekosystem.vista;

import java.awt.Dimension;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.*;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import korekosystem.KorekoSystem;
import korekosystem.modelo.Cliente;
import korekosystem.modelo.Cobro;
import net.coderazzi.filters.gui.TableFilterHeader;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JRViewer;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.util.SimpleFileResolver;
import net.sf.jasperreports.view.JRViewer;
import org.jfree.chart.plot.PlotOrientation;

/**
 *
 * @author santiago
 */
public class VentanaPrincipal extends javax.swing.JFrame {

    
    @PersistenceContext
    EntityManager entityMgr;
    /**
     * Creates new form VentanaPrincipal
     */
    String PATH = "/korekosystem/reportes/";
    //String PATH_JDBC = "jdbc:mysql://localhost:3306/anamaria";
    String PATH_JDBC = "jdbc:mysql://212.1.210.181:3306/groupwe_anamaria";
    String user = "groupwe_anamaria";
    String pass = "anamaria";
    
    public VentanaPrincipal() {
        initComponents();
        TableFilterHeader filterHeader = new TableFilterHeader(jTable1);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jDesktopPane1 = new javax.swing.JDesktopPane();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        recargarButton = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        menuListadoCliente = new javax.swing.JMenuItem();
        menuListadoProducto = new javax.swing.JMenuItem();
        menuListadoPagoPorCliente = new javax.swing.JMenuItem();
        menuListadoCobrosPorVendedor = new javax.swing.JMenuItem();
        menuListadoComisionMensual = new javax.swing.JMenuItem();
        menuListadoComprasMes = new javax.swing.JMenuItem();
        menuListadoVentasPorProducto = new javax.swing.JMenuItem();
        menuListadoVentaMes = new javax.swing.JMenuItem();
        menuLibroDiario = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        menuAlertas = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Ana Maria Comercial");
        setPreferredSize(new java.awt.Dimension(1024, 650));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jDesktopPane1.setBackground(new java.awt.Color(255, 0, 102));
        jDesktopPane1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/Barcode.png"))); // NOI18N
        jButton3.setText("Productos");
        jButton3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton3.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jButton3.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton3MouseClicked(evt);
            }
        });
        jButton3.setBounds(650, 30, 120, 100);
        jDesktopPane1.add(jButton3, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/compra.png"))); // NOI18N
        jButton4.setText("Compras");
        jButton4.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton4.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jButton4.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton4.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton4MouseClicked(evt);
            }
        });
        jButton4.setBounds(240, 150, 120, 100);
        jDesktopPane1.add(jButton4, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/pago.png"))); // NOI18N
        jButton5.setText("Cobros");
        jButton5.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton5.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jButton5.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton5.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton5MouseClicked(evt);
            }
        });
        jButton5.setBounds(450, 150, 120, 100);
        jDesktopPane1.add(jButton5, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/venta.png"))); // NOI18N
        jButton6.setText("Ventas");
        jButton6.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton6.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jButton6.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton6.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton6MouseClicked(evt);
            }
        });
        jButton6.setBounds(650, 150, 120, 100);
        jDesktopPane1.add(jButton6, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Nombre", "Dirección", "Saldo Pendiente", "Fecha"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Long.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jScrollPane1.setBounds(130, 300, 770, 260);
        jDesktopPane1.add(jScrollPane1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel1.setFont(new java.awt.Font("Good Times", 1, 14)); // NOI18N
        jLabel1.setText("Cobros Pendientes");
        jLabel1.setBounds(410, 250, 360, 30);
        jDesktopPane1.add(jLabel1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/client.png"))); // NOI18N
        jButton1.setText("Clientes");
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });
        jButton1.setBounds(240, 30, 120, 100);
        jDesktopPane1.add(jButton1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/Preppy.png"))); // NOI18N
        jButton2.setText("Vendedores");
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton2MouseClicked(evt);
            }
        });
        jButton2.setBounds(450, 30, 120, 100);
        jDesktopPane1.add(jButton2, javax.swing.JLayeredPane.DEFAULT_LAYER);

        recargarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/refresh.png"))); // NOI18N
        recargarButton.setText("Recargar");
        recargarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                recargarButtonActionPerformed(evt);
            }
        });
        recargarButton.setBounds(700, 570, 200, 27);
        jDesktopPane1.add(recargarButton, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jMenu1.setText("Principal");

        jMenuItem1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/eliminar.png"))); // NOI18N
        jMenuItem1.setText("Salir");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Informes");
        jMenu2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu2ActionPerformed(evt);
            }
        });

        menuListadoCliente.setText("Listado Clientes");
        menuListadoCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuListadoClienteActionPerformed(evt);
            }
        });
        jMenu2.add(menuListadoCliente);

        menuListadoProducto.setLabel("Listado Productos");
        menuListadoProducto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuListadoProductoActionPerformed(evt);
            }
        });
        jMenu2.add(menuListadoProducto);

        menuListadoPagoPorCliente.setText("Listado Pagos por Cliente");
        menuListadoPagoPorCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuListadoPagoPorClienteActionPerformed(evt);
            }
        });
        jMenu2.add(menuListadoPagoPorCliente);

        menuListadoCobrosPorVendedor.setText("Listado Cobros por Vendedor");
        menuListadoCobrosPorVendedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuListadoCobrosPorVendedorActionPerformed(evt);
            }
        });
        jMenu2.add(menuListadoCobrosPorVendedor);

        menuListadoComisionMensual.setText("Listado Comisión Mensual Vendedor");
        menuListadoComisionMensual.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuListadoComisionMensualActionPerformed(evt);
            }
        });
        jMenu2.add(menuListadoComisionMensual);

        menuListadoComprasMes.setText("Listado Compras por Mes");
        menuListadoComprasMes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuListadoComprasMesActionPerformed(evt);
            }
        });
        jMenu2.add(menuListadoComprasMes);

        menuListadoVentasPorProducto.setText("Listado Ventas por Producto");
        menuListadoVentasPorProducto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuListadoVentasPorProductoActionPerformed(evt);
            }
        });
        jMenu2.add(menuListadoVentasPorProducto);

        menuListadoVentaMes.setText("Listado Ventas por Mes");
        menuListadoVentaMes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuListadoVentaMesActionPerformed(evt);
            }
        });
        jMenu2.add(menuListadoVentaMes);

        menuLibroDiario.setText("Libro Diario");
        menuLibroDiario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuLibroDiarioActionPerformed(evt);
            }
        });
        jMenu2.add(menuLibroDiario);

        jMenuBar1.add(jMenu2);

        jMenu3.setText("Alertas");

        menuAlertas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/calendar.png"))); // NOI18N
        menuAlertas.setText("Alertas");
        menuAlertas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuAlertasActionPerformed(evt);
            }
        });
        jMenu3.add(menuAlertas);

        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jDesktopPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1024, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jDesktopPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 649, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
        // TODO add your handling code here:
        ABMCliente vcliente = new ABMCliente();
        vcliente.pack();
        this.jDesktopPane1.add(vcliente);
        vcliente.setClosable(true);
        vcliente.setVisible(true);

    }//GEN-LAST:event_jButton1MouseClicked

    private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked
        // TODO add your handling code here:
        ABMProducto vproducto = new ABMProducto();
        vproducto.pack();
        this.jDesktopPane1.add(vproducto);
        vproducto.setClosable(true);
        vproducto.setVisible(true);
    }//GEN-LAST:event_jButton3MouseClicked

    private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked
        // TODO add your handling code here:
        ABMVendedor vvendedor = new ABMVendedor();
        vvendedor.pack();
        this.jDesktopPane1.add(vvendedor);
        vvendedor.setClosable(true);
        vvendedor.setVisible(true);
    }//GEN-LAST:event_jButton2MouseClicked

    private void jButton5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton5MouseClicked
        // TODO add your handling code here:
        ABMCobro vcobro = new ABMCobro();
        vcobro.pack();
        this.jDesktopPane1.add(vcobro);
        vcobro.setClosable(true);
        vcobro.setVisible(true);
    }//GEN-LAST:event_jButton5MouseClicked

    private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton4MouseClicked
        // TODO add your handling code here:
        ABMCompra vcompra = new ABMCompra();
        vcompra.pack();
        this.jDesktopPane1.add(vcompra);
        vcompra.setClosable(true);
        vcompra.setVisible(true);
    }//GEN-LAST:event_jButton4MouseClicked

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
                if (entityMgr != null && entityMgr.isOpen()) {
                    entityMgr.close();
                }
    }//GEN-LAST:event_formWindowClosed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
                VentanaPrincipal estaVentana =
                        (VentanaPrincipal) evt.getSource();
                try {
                    entityMgr = Persistence
                            .createEntityManagerFactory("KorekoSystemPU")
                            .createEntityManager();
                    estaVentana.recargarTabla();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(estaVentana,
                            "Error al inciar el motor de persistencia\n [" +
                            e.getMessage() + "]");
                    estaVentana.dispose();
                }
    }//GEN-LAST:event_formWindowOpened

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void menuListadoClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuListadoClienteActionPerformed
        // TODO add your handling code here:
       /* SimpleDateFormat formato = new SimpleDateFormat("dd-MM-yyyy");
        Query q = entityMgr.createNamedQuery("Cliente.findAll");
        List<Cliente> lista = q.getResultList();
        
        try 
        { 
            JasperReport reporte = (JasperReport) JRLoader.loadObject(KorekoSystem.class.getResourceAsStream(PATH + "reporte-cliente.jasper")); 
            JasperPrint reportePrint = JasperFillManager.fillReport(reporte, null, new JRBeanCollectionDataSource(lista)); 
            //JRExporter exporter = new JRPdfExporter(); 
            //exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            //String nombreArchivo = "LISTADO-CLIENTES-" + formato.format(new Date()) + ".pdf";
            //exporter.setParameter(JRExporterParameter.OUTPUT_FILE, new java.io.File(nombreArchivo)); 
            //exporter.exportReport();
            
            //JOptionPane.showMessageDialog(this,
            //                "Informe creado con Exito\n El informe '" + nombreArchivo + "' fue creado");
            
            //Viewer for JasperReport
            JRViewer reportePrintV = new JRViewer(reportePrint);
            
            //Insert viewer to a JFrame to make it showable
            JFrame jf = new JFrame();
            jf.getContentPane().add(reportePrintV);
            jf.validate();
            jf.setVisible(true);
            jf.setSize(new Dimension(800,600));
	    jf.setLocation(300,100);
	    jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        } 
        catch(JRException e) 
        { 
            JOptionPane.showMessageDialog(this,
                            "Error en el sistema\n [" +
                            e.getMessage() + "]");
            e.printStackTrace();
        
        } 
        */
        
        SimpleDateFormat formato = new SimpleDateFormat("dd-MM-yyyy");
     
        try 
        { 
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection conexion = DriverManager.getConnection(PATH_JDBC, user, pass);

            JasperReport reporte = (JasperReport) JRLoader.loadObject(KorekoSystem.class.getResourceAsStream(PATH + "reporte-cliente.jasper")); 
            
            JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, null, conexion); 
            JRExporter exporter = new JRPdfExporter(); 
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
                String nombreArchivo = "LISTADO-CLIENTES-" + formato.format(new Date()) + ".pdf";
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE, new java.io.File(nombreArchivo)); 
            exporter.exportReport();
            
            JOptionPane.showMessageDialog(this,
                            "Informe creado con Exito\n El informe '" + nombreArchivo + "' fue creado");
           
            //Viewer for JasperReport
            JRViewer reportePrintV = new JRViewer(jasperPrint);
            
            //Insert viewer to a JFrame to make it showable
            JFrame jf = new JFrame();
            jf.getContentPane().add(reportePrintV);
            jf.validate();
            jf.setVisible(true);
            jf.setSize(new Dimension(800,600));
	    jf.setLocation(300,100);
	    jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        } 
        catch(Exception e) 
        { 
            JOptionPane.showMessageDialog(this,
                            "Error en el sistema\n [" +
                            e.getMessage() + "]");
            e.printStackTrace();
            
        }
    }//GEN-LAST:event_menuListadoClienteActionPerformed

    private void jButton6MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton6MouseClicked
        // TODO add your handling code here:
        ABMVenta vventa = new ABMVenta();
        vventa.pack();
        this.jDesktopPane1.add(vventa);
        vventa.setClosable(true);
        vventa.setVisible(true);
    }//GEN-LAST:event_jButton6MouseClicked

    private void recargarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_recargarButtonActionPerformed
        // TODO add your handling code here:
        recargarTabla();
    }//GEN-LAST:event_recargarButtonActionPerformed

    private void menuListadoPagoPorClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuListadoPagoPorClienteActionPerformed
        // TODO add your handling code here:
        SimpleDateFormat formato = new SimpleDateFormat("dd-MM-yyyy");
     
        try 
        {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection conexion = DriverManager.getConnection(PATH_JDBC, user, pass);

            JasperReport reporte = (JasperReport) JRLoader.loadObject(KorekoSystem.class.getResourceAsStream(PATH + "reporte-Pago-Cliente.jasper")); 
            
            JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, null, conexion); 
            JRExporter exporter = new JRPdfExporter(); 
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            String nombreArchivo = "LISTADO-PAGOS-CLIENTES-" + formato.format(new Date()) + ".pdf";
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE, new java.io.File(nombreArchivo)); 
            exporter.exportReport();
            
            JOptionPane.showMessageDialog(this,
                            "Informe creado con Exito\n El informe '" + nombreArchivo + "' fue creado");
            
            //Viewer for JasperReport
            JRViewer reportePrintV = new JRViewer(jasperPrint);
            
            //Insert viewer to a JFrame to make it showable
            JFrame jf = new JFrame();
            jf.getContentPane().add(reportePrintV);
            jf.validate();
            jf.setVisible(true);
            jf.setSize(new Dimension(800,600));
	    jf.setLocation(300,100);
	    jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            
        } 
        catch(Exception e) 
        { 
            JOptionPane.showMessageDialog(this,
                            "Error en el sistema\n [" +
                            e.getMessage() + "]");
            e.printStackTrace();
            
        }
    }//GEN-LAST:event_menuListadoPagoPorClienteActionPerformed

    private void menuListadoCobrosPorVendedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuListadoCobrosPorVendedorActionPerformed
      // TODO add your handling code here:
        
        SimpleDateFormat formato = new SimpleDateFormat("dd-MM-yyyy");
     
        try 
        {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection conexion = DriverManager.getConnection(PATH_JDBC, user, pass);

            JasperReport reporte = (JasperReport) JRLoader.loadObject(KorekoSystem.class.getResourceAsStream(PATH + "reporte-detalles-cobros.jasper")); 
            
            JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, null, conexion); 
            JRExporter exporter = new JRPdfExporter(); 
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            String nombreArchivo = "LISTADO-COBROS-VENDEDORES-" + formato.format(new Date()) + ".pdf";
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE, new java.io.File(nombreArchivo)); 
            exporter.exportReport();
            
            JOptionPane.showMessageDialog(this,
                            "Informe creado con Exito\n El informe '" + nombreArchivo + "' fue creado");
            
            
            //Viewer for JasperReport
            JRViewer reportePrintV = new JRViewer(jasperPrint);
            
            //Insert viewer to a JFrame to make it showable
            JFrame jf = new JFrame();
            jf.getContentPane().add(reportePrintV);
            jf.validate();
            jf.setVisible(true);
            jf.setSize(new Dimension(800,600));
	    jf.setLocation(300,100);
	    jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            
        } 
        catch(Exception e) 
        { 
            JOptionPane.showMessageDialog(this,
                            "Error en el sistema\n [" +
                            e.getMessage() + "]");
            e.printStackTrace();
            
        }
    }//GEN-LAST:event_menuListadoCobrosPorVendedorActionPerformed

    private void menuListadoComprasMesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuListadoComprasMesActionPerformed
     
        compraxmes_prueba compraMes = new compraxmes_prueba();
        compraMes.pack();
       // this.jDesktopPane1.add(compraMes);
        //compraMes.setClosable(true);
        compraMes.setVisible(true);

     
    }//GEN-LAST:event_menuListadoComprasMesActionPerformed

    private void menuListadoComisionMensualActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuListadoComisionMensualActionPerformed
        // TODO add your handling code here:
        SimpleDateFormat formato = new SimpleDateFormat("dd-MM-yyyy");
     
        try 
        {            
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection conexion = DriverManager.getConnection(PATH_JDBC, user, pass);

            JasperReport reporte = (JasperReport) JRLoader.loadObject(KorekoSystem.class.getResourceAsStream(PATH + "reporte-Cobro-Vendedor.jasper")); 
            
            JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, null, conexion); 
            JRExporter exporter = new JRPdfExporter(); 
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            String nombreArchivo = "LISTADO-COMISION-VENDEDORES-" + formato.format(new Date()) + ".pdf";
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE, new java.io.File(nombreArchivo)); 
            exporter.exportReport();
            
            JOptionPane.showMessageDialog(this,
                            "Informe creado con Exito\n El informe '" + nombreArchivo + "' fue creado");
          
            //Viewer for JasperReport
            JRViewer reportePrintV = new JRViewer(jasperPrint);
            
            //Insert viewer to a JFrame to make it showable
            JFrame jf = new JFrame();
            jf.getContentPane().add(reportePrintV);
            jf.validate();
            jf.setVisible(true);
            jf.setSize(new Dimension(800,600));
	    jf.setLocation(300,100);
	    jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            
        } 
        catch(Exception e) 
        { 
            JOptionPane.showMessageDialog(this,
                            "Error en el sistema\n [" +
                            e.getMessage() + "]");
            e.printStackTrace();
            
        }
    }//GEN-LAST:event_menuListadoComisionMensualActionPerformed

    private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jMenu2ActionPerformed

    private void menuListadoVentasPorProductoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuListadoVentasPorProductoActionPerformed
        // TODO add your handling code here:
        SimpleDateFormat formato = new SimpleDateFormat("dd-MM-yyyy");
     
        try 
        { 
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection conexion = DriverManager.getConnection(PATH_JDBC, user, pass);

            JasperReport reporte = (JasperReport) JRLoader.loadObject(KorekoSystem.class.getResourceAsStream(PATH + "reporte-ventaxproducto_1.jasper")); 
            
            JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, null, conexion); 
            JRExporter exporter = new JRPdfExporter(); 
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            String nombreArchivo = "LISTADO-VENTAS-PRODUCTOS-" + formato.format(new Date()) + ".pdf";
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE, new java.io.File(nombreArchivo)); 
            exporter.exportReport();
            
            JOptionPane.showMessageDialog(this,
                            "Informe creado con Exito\n El informe '" + nombreArchivo + "' fue creado");
            
            //Viewer for JasperReport
            JRViewer reportePrintV = new JRViewer(jasperPrint);
            
            //Insert viewer to a JFrame to make it showable
            JFrame jf = new JFrame();
            jf.getContentPane().add(reportePrintV);
            jf.validate();
            jf.setVisible(true);
            jf.setSize(new Dimension(800,600));
	    jf.setLocation(300,100);
	    jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        } 
        catch(Exception e) 
        { 
            JOptionPane.showMessageDialog(this,
                            "Error en el sistema\n [" +
                            e.getMessage() + "]");
            e.printStackTrace();
            
        }
    }//GEN-LAST:event_menuListadoVentasPorProductoActionPerformed

    private void menuListadoVentaMesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuListadoVentaMesActionPerformed
        // TODO add your handling code here:
        ventaxmes ventaMes = new ventaxmes();
        ventaMes.pack();
        ventaMes.setVisible(true);
    }//GEN-LAST:event_menuListadoVentaMesActionPerformed

    private void menuLibroDiarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuLibroDiarioActionPerformed
        // TODO add your handling code here:
        balance balancexmes = new balance();
        balancexmes.pack();
        balancexmes.setVisible(true);        
    }//GEN-LAST:event_menuLibroDiarioActionPerformed

    private void menuListadoProductoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuListadoProductoActionPerformed
        // TODO add your handling code here:
        SimpleDateFormat formato = new SimpleDateFormat("dd-MM-yyyy");
     
        try 
        { 
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection conexion = DriverManager.getConnection(PATH_JDBC, user, pass);

            JasperReport reporte = (JasperReport) JRLoader.loadObject(KorekoSystem.class.getResourceAsStream(PATH + "reporte-producto.jasper")); 
            
            JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, null, conexion); 
            JRExporter exporter = new JRPdfExporter(); 
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            String nombreArchivo = "LISTADO-PRODUCTOS-" + formato.format(new Date()) + ".pdf";
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE, new java.io.File(nombreArchivo)); 
            exporter.exportReport();
            
            JOptionPane.showMessageDialog(this,
                            "Informe creado con Exito\n El informe '" + nombreArchivo + "' fue creado");
           
            //Viewer for JasperReport
            JRViewer reportePrintV = new JRViewer(jasperPrint);
            
            //Insert viewer to a JFrame to make it showable
            JFrame jf = new JFrame();
            jf.getContentPane().add(reportePrintV);
            jf.validate();
            jf.setVisible(true);
            jf.setSize(new Dimension(800,600));
	    jf.setLocation(300,100);
	    jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        } 
        catch(Exception e) 
        { 
            JOptionPane.showMessageDialog(this,
                            "Error en el sistema\n [" +
                            e.getMessage() + "]");
            e.printStackTrace();
            
        }
    }//GEN-LAST:event_menuListadoProductoActionPerformed

    private void menuAlertasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuAlertasActionPerformed
        // Abrimos la ventana de Alertas
        AlertasDiaForm valertas = new AlertasDiaForm();
        valertas.pack();
        valertas.setVisible(true);
    }//GEN-LAST:event_menuAlertasActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new VentanaPrincipal().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JDesktopPane jDesktopPane1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JMenuItem menuAlertas;
    private javax.swing.JMenuItem menuLibroDiario;
    private javax.swing.JMenuItem menuListadoCliente;
    private javax.swing.JMenuItem menuListadoCobrosPorVendedor;
    private javax.swing.JMenuItem menuListadoComisionMensual;
    private javax.swing.JMenuItem menuListadoComprasMes;
    private javax.swing.JMenuItem menuListadoPagoPorCliente;
    private javax.swing.JMenuItem menuListadoProducto;
    private javax.swing.JMenuItem menuListadoVentaMes;
    private javax.swing.JMenuItem menuListadoVentasPorProducto;
    private javax.swing.JButton recargarButton;
    // End of variables declaration//GEN-END:variables

    private void recargarTabla() {
        try{
            Query q = entityMgr.createNamedQuery("Cobro.findByPendiente");
            q.setParameter("pendiente", true);
            
            int diferenciaEnDias = 10;
            Date fechaActual = Calendar.getInstance().getTime();
            long tiempoActual = fechaActual.getTime();
            long unDia = diferenciaEnDias * 24 * 60 * 60 * 1000;
            Date fechaInicio = new Date(tiempoActual - unDia);
            Date fechaFin = new Date(tiempoActual + unDia);
            SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");

            
            List<Cobro> result = q.getResultList();
            // se obtiene la referencia al modelo de datos
            DefaultTableModel tm = ((DefaultTableModel)jTable1.getModel());
            // se descartan la filas existentes
            tm.setRowCount(0);

            // se añaden los datos obtenidos si es que existen
            // cada fila recuperada es un array de Object[]
            System.out.println(q.getResultList().size());
            System.out.println("Ya tengo los resultados supuestamente");
            for (Cobro o : result) {
                System.out.println("-->"+o.getFecha());
                if(o.getFecha().after(fechaInicio) && o.getFecha().before(fechaFin)){
                    // Agregamos a un vector las propiedades
                    Vector v = new Vector();
                    v.add(o.getCliente().getNombre() + " " + o.getCliente().getApellido());
                    v.add(o.getCliente().getDireccion());
                    v.add(o.getCliente().getSaldo());
                    String f = formato.format(o.getFecha());
                    v.add(f);
                    // Agregamos ese vector como columna
                    tm.addRow(v);
               }
            }
        }catch(Exception e){
            JOptionPane.showMessageDialog(this,
                            "Error en el sistema\n [" +
                            e.getMessage() + "]");
                    this.dispose();
        }

    }
}
